import { getApi } from "../../services/autoApi";
import { CODE_SUCCESS } from "../../utils/consts";

// 字典批量查询接口地址
const patchDict = "/dict/getDicByTypes";
const vin = "/workOrder/queryVehicleInfo";
const repairHisUrl = "/workOrder/queryOrderWarranty";
const initCarOrderSelect = "/vehicleAppraisal/getWorkMessage";
const initPartOrderSelect = "/partsWarranty/queryAssociationOrder";

const vinChange = function vinSearch() {
  if (!this.formModel || !this.formModel.vin) return;
  if (this.formModel?.vin?.length !== 17) return;
  // 查询配件信息
  getApi(vin, { vin: this.formModel.vin }).then((res) => {
    const { code, message, data } = res.data;
    if (code === CODE_SUCCESS && data) {
      const recordKeys = Object.keys(data);
      Array.prototype.forEach.call(recordKeys, (item) => {
        const des = Object.getOwnPropertyDescriptor(this.formModel, item);
        if (des) {
          (0, this.formModel)[item] = data[item];
        }
      });
    }
    if (code !== CODE_SUCCESS) this.$message.error(message);
  });
  // 初始化可以选订单
  // 查询维修记录-此处不需要提交
  getApi(repairHisUrl, { vin: this.formModel.vin }).then((res) => {
    const { code, message, data } = res.data;
    if (code === CODE_SUCCESS && data) {
      const his = Array.prototype.map.call(data, (item, i) => {
        const tmp = item;
        tmp.id = i;
        return tmp;
      });
      this.$set(this.apiData, "repairHis", his);
    }
    if (code !== CODE_SUCCESS) this.$message.error(message);
  });
  if (this.formModel.workOrderType === "5") {
    getApi(initCarOrderSelect, { vin: this.formModel.vin }).then((res) => {
      const { code, data } = res.data;
      if (code !== CODE_SUCCESS) return;
      const {
        rescueWorkOrderList,
        partCallWorkOrderList,
        superAppovalWorkOrderList
      } = data;
      const rescueWorkOrderListOption = rescueWorkOrderList.map((item) => ({
        text: item.workId,
        value: item.workId,
        fee: item.totalCost
      }));
      const partCallWorkOrderListOption = partCallWorkOrderList.map((item) => ({
        text: item.workId,
        value: item.workId,
        fee: item.totalCost
      }));
      const superAppovalWorkOrderListOption = superAppovalWorkOrderList.map(
        (item) => ({
          text: item.workId,
          value: item.workId,
          fee: item.totalCost
        })
      );
      this.$set(
        this.selectOptions,
        "workRescueWorkId",
        rescueWorkOrderListOption
      );
      this.$set(
        this.selectOptions,
        "partsCallWorkId",
        partCallWorkOrderListOption
      );
      this.$set(
        this.selectOptions,
        "superApprovalWorkId",
        superAppovalWorkOrderListOption
      );
    });
  }
  if (this.formModel.workOrderType === "12") {
    getApi(initPartOrderSelect, { vin: this.formModel.vin }).then((res) => {
      const { code, data } = res.data;
      if (code !== CODE_SUCCESS) return;
      const { partsOrderList, superAppovalWorkOrderList } = data;
      const partsOrderListOption = partsOrderList.map((item) => ({
        text: item.code,
        value: item.code
      }));
      const superAppovalWorkOrderListOption = superAppovalWorkOrderList.map(
        (item) => ({ text: item.code, value: item.code })
      );
      this.$set(this.selectOptions, "partsOrderWorkId", partsOrderListOption);
      this.$set(
        this.selectOptions,
        "superApprovalWorkId",
        superAppovalWorkOrderListOption
      );
    });
  }
};
export default {
  watch: {
    "formModel.vin": vinChange
  },
  methods: {
    flatinputs() {
      let inputsObjs = [];
      Array.prototype.forEach.call(this.config, (item) => {
        if (item.inputs) {
          inputsObjs = inputsObjs.concat(item.inputs);
        }
      });
      return inputsObjs;
    },
    setRulesAndForm() {
      const inputs = this.flatinputs();
      Array.prototype.forEach.call(inputs, (item) => {
        const newRules = Array.prototype.map.call(item.rules || [], (rule) => {
          let combinedRule;
          if (rule) {
            combinedRule = { ...rule };
            if (combinedRule && combinedRule.required) {
              const type = item.type || "input";
              combinedRule.message =
                (0, combinedRule.message)[type] + item.label;
            }
          }
          return combinedRule;
        });
        this.$set(this.rules, item.inputName, newRules);
        this.$set(this.formModel, item.inputName, item.value);
        if (item.hooks) {
          (0, this.formModelHooks)[item.inputName] = item.hooks;
        }
      });
    },
    initStationInfo() {
      if (this.actionType !== "add") return;
      getApi("/merchant/getMerchant").then((res) => {
        const { code, message, data } = res.data;
        if (code === CODE_SUCCESS) {
          const { stationCode, serviceStationStar, basicName } = data;
          this.formModel.stationCode = stationCode;
          this.formModel.stationCode = stationCode;
          this.formModel.serviceStationName = basicName;
          this.formModel.serviceStationStar = serviceStationStar;
          return;
        }
      });
      if (dictTypeSet.size > 0) {
        const dictTypes = [...dictTypeSet].join(",");
        getApi(patchDict, { dictTypes }).then((res) => {
          const { data, code } = res.data;
          if (code === CODE_SUCCESS) {
            const dictTypeKeys = [...dictInputMap.keys()];
            Array.prototype.forEach.call(dictTypeKeys, (item) => {
              const options = data[dictInputMap.get(item)].map((opt) => ({
                value: opt.code,
                text: opt.name
              }));
              this.$set(this.selectOptions, item, options);
            });
            return;
          }
          this.$message.error("部分下拉选项初始化失败，请重试！");
        });
      }
    },
    async initOptions() {
      const dictTypeSet = new Set();
      const dictInputMap = new Map();
      const inputs = this.flatinputs();
      Array.prototype.forEach.call(inputs || [], (item) => {
        // 需要单独调其他接口的字典
        if (item.type === "select" && item.optionUrl) {
          // 此处应该优化为批量接口-目前后端无批量接口
          getApi(item.optionUrl, item.optionParams).then((res) => {
            const { data, code } = res.data;
            if (code === CODE_SUCCESS) {
              const options = data.map((opt) => ({
                value: opt.code,
                text: opt.name
              }));
              this.$set(this.selectOptions, item.inputName, options);
              return;
            }
            this.$message.error(`${item.label}下拉选项初始化失败,请重试！`);
          });
        }
        // 不需要单独调接口的字典批量处理
        if (item.type === "select" && item.dict) {
          dictTypeSet.add(item.dict);
          dictInputMap.set(item.inputName, item.dict);
        }
      });
      if (dictTypeSet.size > 0) {
        const dictTypes = [...dictTypeSet].join(",");
        getApi(patchDict, { dictTypes }).then((res) => {
          const { data, code } = res.data;
          if (code === CODE_SUCCESS) {
            const dictTypeKeys = [...dictInputMap.keys()];
            Array.prototype.forEach.call(dictTypeKeys, (item) => {
              const options = data[dictInputMap.get(item)].map((opt) => ({
                value: opt.code,
                text: opt.name
              }));
              this.$set(this.selectOptions, item, options);
            });
            return;
          }
          this.$message.error("部分下拉选项初始化失败，请重试！");
        });
      }
    },
    init() {
      this.setRulesAndForm();
      this.initStationInfo();
      this.initOptions();
    }
  }
};
